// src\components\News\Editor.jsx
import React,{useEffect,useState} from 'react'
import { Editor } from 'react-draft-wysiwyg';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
import { EditorState, convertToRaw, ContentState } from 'draft-js';
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';
// 自定义样式
import './NewsEditor.css'
export default function NewsEditor(props) {
  const [editorState,setEditorState]=useState("");

  useEffect(() => {
    // 初始化富文本
    const html = props.content;
    if (html === undefined) return
    const contentBlock = htmlToDraft(html);
    if (contentBlock) {
      const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
      const editorState = EditorState.createWithContent(contentState);
      setEditorState(editorState)
    }
  }, [props.content])
  return (
    <div>
      <Editor
        editorState={editorState}
        toolbarClassName="toolbarClassName"
        wrapperClassName="wrapperClassName"
        editorClassName="editorClassName"
        onEditorStateChange={(editorContent) => setEditorState(editorContent)}

        onBlur={() => {
          // console.log()
          // 失去焦点时，把内容传给父组件

          props.getContent(draftToHtml(convertToRaw(editorState.getCurrentContent())));
        }}
      />
    </div>
  )
}
